﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WinFormClient.ServiceReference1;

namespace WinFormClient
{
    //这个没用 没想好这个有什么用;
    public class ClientEventArgs : EventArgs
    {
        public enum EventType
        {
            TOPIC,
            GROUP,
            MESSAGE,
         }
        public EventType type;
        public WinFormClient.ClientEventArgs.EventType Type
        {
            get { return type; }
            set { type = value; }
        }
        public string content;
        public string Content
        {
            get { return content; }
            set { content = value; }
        }
        public Message msg;
        public Message Message
        {
            get { return msg; }
            set { msg = value; }
        }
    }

    /// <summary>
    /// 客户端的整体调度类，用于沟通界面和内部数据
    /// </summary>
    public class Client : WinFormClient.IViewController
    {
        public int debug;
        ClientDataCenter myDataCenter;
        
        //public event EventHandler<ClientEventArgs> ShowMsg;
        /// <summary>
        /// 加载完成。 sender 对象为 GroupSet
        /// </summary>
        public event EventHandler FinishedLoadGroup;
        /// <summary>
        /// 加载完成。 sender 对象为 TopicSet
        /// </summary>
        public event EventHandler FinishedLoadTopic;
        /// <summary>
        /// 加载完成。 sender 对象为 MesageSet
        /// </summary>
        public event EventHandler FinishedLoadReplies;
        /// <summary>
        /// 加载完成。 sender 对象为 UserInfo
        /// </summary>
        public event EventHandler FinishedLoadUserInfo;
        /// <summary>
        /// 出现各种错误。sender 对象为错误信息的string
        /// </summary>
        public event EventHandler ShowErrorMsg;
        /// <summary>
        /// 登录成功，可以开始加载主窗口
        /// </summary>
        //public event EventHandler LoginSuccess;
        /// <summary>
        /// 注册成功，可以登录
        /// </summary>
        //public event EventHandler SignUpSuccess;

        int topicsPerPage;
        public int TopicsPerPage
        {
            get { return topicsPerPage; }
            set { topicsPerPage = value; }
        }
        int msgsPerPage;
        public int MsgsPerPage
        {
            get { return msgsPerPage; }
            set { msgsPerPage = value; }
        }

        Dictionary<int,int> msgsSoFar;
        Dictionary<int, int> currentTopicPage;

        public Client()
        {
            myDataCenter = new ClientDataCenter();
            msgsSoFar = new Dictionary<int, int>();
            currentTopicPage = new Dictionary<int, int>();
        }
        /// <summary>
        /// 开始从本地加载用户信息
        /// </summary>
        public void FetchUserInfo()
        {
            UserInfo user;
            user = myDataCenter.data.userinfo;
            if(!String.IsNullOrEmpty(user.UserName))FinishedLoadUserInfo(user, null);
        }
        /// <summary>
        /// 尝试登录
        /// </summary>
        /// <param name="username">不解释</param>
        /// <param name="password">不解释</param>
        public LoginState Login(string username, string password)
        {
            RESULTINFO result;
            LoginState state;
            myDataCenter.data.userinfo.UserName = username;
            myDataCenter.data.userinfo.Password = password;
            //else ShowErrorMsg("登录失败", null);
            state = myDataCenter.TryLogin(out result);
            if (state != LoginState.LOGIN)
            {
                myDataCenter.data.userinfo.Password = password.GetHashCode().ToString();
                state = myDataCenter.TryLogin(out result);
                if (state != LoginState.LOGIN)
                {
                    myDataCenter.data.userinfo = new UserInfo("", "");
                }
            }
            return state;
            //throw new NotImplementedException();
        }
        /// <summary>
        /// 开始加载Groups
        /// </summary>
        public void FetchGroups()
        {
            RESULTINFO result;
            GroupSet groups = new GroupSet();
            if (0 == myDataCenter.TryGetGroups(out groups, out result))
                FinishedLoadGroup(groups, null);
            else ShowErrorMsg("载入分组失败", null);
        }
        /// <summary>
        /// 登出
        /// </summary>
        public void Exit()
        {
            myDataCenter.LocalSave();
        }

        public void FetchTopics(int groupid, int a, int b)
        {
            RESULTINFO result;
            if (TopicsPerPage != 0)
            {
                TopicSet topics = new TopicSet();
                topics.group = new WinFormClient.ServiceReference1.Group();
                topics.group.id = groupid;
                if (0 == myDataCenter.TryGetTopics(groupid, a, b, out topics, out result)) FinishedLoadTopic(topics, null);
                else ShowErrorMsg("载入主题列表失败", null);
            }
            else
            {
                ShowErrorMsg("内部错误，未设置每页Topic数", null);
            }
        }

        /// <summary>
        /// 开始加载Topics
        /// </summary>
        /// <param name="groupid">不解释</param>
        /// <param name="page">请求页数，默认为最前一页</param>
        public void FetchTopics(int groupid, int page = 1)
        {
            RESULTINFO result;
            if (TopicsPerPage != 0)
            {
                TopicSet topics = new TopicSet();
                topics.group = new WinFormClient.ServiceReference1.Group();
                topics.group.id = groupid;
                if (!currentTopicPage.ContainsKey(groupid)) currentTopicPage.Add(groupid, page);
                else currentTopicPage[groupid] = page;
                if (0 == myDataCenter.TryGetTopics(groupid, topicsPerPage * (page - 1), topicsPerPage * page, out topics, out result)) FinishedLoadTopic(topics, null);
                else ShowErrorMsg("载入主题列表失败", null);
            }
            else
            {
                ShowErrorMsg("内部错误，未设置每页Topic数", null);
            }
            //throw new System.NotImplementedException();
        }

        void FetchRecentTopics(int groupid)
        {
            int page;
            if (currentTopicPage.ContainsKey(groupid))
            {
                page = currentTopicPage[groupid];
            }
            else page = 1;
            FetchTopics(groupid, page);
        }
        /// <summary>
        /// 开始加载Mesages（历史记录模式）
        /// </summary>
        /// <param name="topicid">不解释</param>
        /// <param name="msgsPP">每页的消息数</param>
        /// <param name="page">页数，默认为最新一页</param>
        //void FetchReplies(int topicid, int msgsPP, int page = 0)
        /// <summary>
        /// 开始加载Mesages（聊天窗口模式）
        /// </summary>
        /// <param name="topicid">不解释</param>
        /// <param name="lastmsgs">倒数信息数</param>
        public void FetchReplies(int topicid, int lastmsgs)
        {
            RESULTINFO result;
            MessageSet msgs = new MessageSet();
            //msgs.topic = new WinFormClient.ServiceReference1.Topic();
            //msgs.topic.id = topicid;
            if (0 == myDataCenter.TryGetMessages(topicid,1, lastmsgs, SortForm.LAST, out msgs, out result))
            { FinishedLoadReplies(msgs, null); msgsSoFar.Add(topicid, msgs.Messages.Length); }
            else ShowErrorMsg("载入消息列表失败", null);
            //throw new System.NotImplementedException();
        }

        void FetchRecentReplies(int topicid)
        {
            RESULTINFO result;
            int msgidsince = msgsSoFar[topicid];
            MessageSet msgs = new MessageSet();
            msgs.topic = new WinFormClient.ServiceReference1.Topic();
            msgs.topic.id = topicid;
            if (0 == myDataCenter.TryGetMessages(topicid,msgidsince + 1, msgidsince + 100, SortForm.DEFAULT, out msgs, out result))
            { FinishedLoadReplies(msgs, null); msgsSoFar[topicid] += msgs.Messages.Length; }
            else ShowErrorMsg("载入消息列表失败", null);
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="topicid">不解释</param>
        /// <param name="msg">要发送的消息</param>
        public void AddReply(int topicid, string msg)
        {
            RESULTINFO result;
            Message m = new Message();
            m.content = msg;
            m.topicId=topicid;
            myDataCenter.TryAddMesseage(m, out result);
            FetchRecentReplies(topicid);
        }
        /// <summary>
        /// 尝试添加一个Topic
        /// </summary>
        /// <param name="topictitle">Topic标题</param>
        /// <param name="groupid">所在GroupID，这个id可以存在ListBox列表项的tag属性里</param>
        public void AddTopic(string topictitle, int groupid)
        {
            RESULTINFO result;
            Topic topic = new Topic();
            topic.groupId = groupid;
            topic.title = topictitle;
            CreateState s = myDataCenter.TryAddTopic(topic, out result);
            if (s == CreateState.Pass) FetchRecentTopics(groupid);
            else ShowErrorMsg(s.ToString(), null);
            //ShowErrorMsg("添加主题失败", null);            
            //throw new System.NotImplementedException();
        }
        /// <summary>
        /// 尝试添加一个Topic（未实现）
        /// </summary>
        /// <param name="topicid"></param>
        /// <param name="groupid"></param>
        public void DeleteTopic(int topicid, int groupid = -1)
        {
            RESULTINFO result;
            ShowErrorMsg("删除Topic功能尚未开放", null);
            //throw new System.NotImplementedException();
        }
        /// <summary>
        /// 尝试注册
        /// </summary>
        /// <param name="username">不解释</param>
        /// <param name="password">不解释</param>
        public AssignState SignUp(string username, string password)
        {
            RESULTINFO result;
            myDataCenter.data.userinfo = new UserInfo(username, password.GetHashCode().ToString());
            //else ShowErrorMsg("注册失败", null);
            return myDataCenter.TrySignUp(out result);
            //throw new System.NotImplementedException();
        }

    }
}
